import socket 

from django.db.models.signals import post_save
from django.template import RequestContext, add_to_builtins
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.conf import settings

from news.models import News
from projects.models import Release, Project, Poll
from comments.models import Comment
from pygameweb.notification.models import Subscription, CHOICES
from utils.redirects import get_tiny_url
from cab.models import Snippet

BLOCKSIZE = 1024
SEND_NEWS = settings.BOT_ENABLE and settings.BOT_SEND_NEWS
SET_TITLE = settings.BOT_ENABLE and settings.BOT_SET_TITLE
SEND_RELEASES = settings.BOT_ENABLE and settings.BOT_SEND_RELEASES
SEND_SNIPPETS = settings.BOT_ENABLE and settings.BOT_SEND_SNIPPETS


def send_to_bot(text):
    if settings.BOT_ENABLE:
        try:
            soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            soc.connect(('127.0.0.1', 7060))
            buf = soc.recv(BLOCKSIZE)
            if buf == "pywbotinterface:ready\n":
                soc.send(text+"\n")
            soc.close()
        except socket.error:
            if settings.DEBUG:
                raise
            
        
#def announce(*args, **kwargs):
#    # kwargs: {'raw': False, 
#    #  'signal': <django.dispatch.dispatcher.Signal object at 0x9f259ec>, 
#    #  'instance': <News: test>, 'sender': <class 'news.models.News'>, 
#    #   'created': True}
#    text = ""
#    if kwargs["created"]:
#        if kwargs["sender"] == News:
#            news = kwargs["instance"]
#            text = 'latest news by %s: "%s"' % (news, 
#                                   news.creator.get_profile().display_name)
#    if text:
#        send_to_bot(text)    
    
    

def check_notifications(sender, instance, created, **kwargs):
    if not created or sender not in (News, Release, Poll, Comment, Snippet):
        return
    obj_id = None
    kind = None
    current_site = Site.objects.get_current()
    if sender == News and instance.active:
        kind = "n"
        url = reverse("news_overview")
        title = "Latest News on %s: %s" % (current_site, instance.title)
        if SEND_NEWS:
            msg = "%s: http://%s%s" % (instance.title, current_site,
                                       get_tiny_url(instance))
            send_to_bot(msg)
        if SET_TITLE:
            msg = "::settitle::"
            send_to_bot(msg)
    elif sender == Release:
        kind = "pr"
        obj_id = instance.project.id
        url = instance.project.get_absolute_url()
        title = "%s released" % instance
        if SEND_RELEASES:
            msg = "%s: http://%s%s" % (title, current_site, 
                                       get_tiny_url(instance))
            send_to_bot(msg)
    elif sender == Poll and not instance.active: # only handle closed polls
        kind = "pm"
        url = reverse("potm-overview")
        title = "Poll notification not yet ready" #TODO: notify on close
    elif sender == Snippet:
        kind = "s"
        url = reverse("snippets")
        title = "Latest Snippet on %s: %s" % (current_site, instance.title)
        if SEND_SNIPPETS:
            msg = "%s: http://%s%s" % (instance.title, current_site,
                                       get_tiny_url(instance))
            send_to_bot(msg)  
    elif sender == Comment and not instance.is_auto_comment():
        obj_id = instance.object_id
        if isinstance(instance.content_object, News):
            kind = "nc"
        elif isinstance(instance.content_object, Project):
            kind = "pc"
        elif isinstance(instance.content_object, Snippet):
            kind = "sc"
        else:
            return
        obj_id = instance.object_id
        url = instance.content_object.get_absolute_url()
        title = str(instance)
    if kind:
        subscriptions = Subscription.objects.by_kind(kind=kind, obj_id=obj_id)
        if not subscriptions:
            return
        args = { 'readable_kind': CHOICES[kind],
                 'instance': instance,
                 'current_site': current_site,
                 'unsubscribe_link': "%s?unsubscribe=%s" % (url, 
                                              CHOICES[kind].replace(" ", "-"))}
        if "c" in kind:
            kind = "c"
        mail_body = render_to_string('notification/mail-%s.txt' % kind, args)
        
        for sub in subscriptions:            	        
            send_mail(title, mail_body % sub.user.get_profile().display_name, 
                      None, [sub.user.email], fail_silently=True)
            
        
        

        

post_save.connect(check_notifications, dispatch_uid="notify_only_once_per_sig")

add_to_builtins('notification.templatetags.subscription_tags')

if __name__ == "__main__":
    send_to_bot("test")